package tuyou.kafka.consumer;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.PartitionInfo;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;
import tuyou.kafka.producer.ProducerTest;

import java.time.Duration;
import java.util.List;
import java.util.Properties;
import java.util.stream.Collectors;

/**
 * kafka独立消费者，一个消费者处理整个topic，防止再均衡
 */
public class ConsumerTest3 {

    public static void main(String[] args) {
        Properties properties = new Properties();
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getCanonicalName());// key反序列化方式
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getCanonicalName());// value反系列化方式
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, ProducerTest.ip);// 指定broker地址，来找到group的coordinator
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, "g1");// 指定用户组

        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(properties);

        List<PartitionInfo> partitionInfoList = consumer.partitionsFor(ProducerTest.topic);
        List<TopicPartition> topicPartitionList = partitionInfoList.stream()
                .map(item -> new TopicPartition(item.topic(), item.partition()))
                .collect(Collectors.toList());
        consumer.assign(topicPartitionList);

        while(true) {
            ConsumerRecords<String, String> poll = consumer.poll(Duration.ofMillis(100));
            for (ConsumerRecord<String, String> record : poll) {
                System.out.printf("topic:%s,partition:%d,key:%s,content:%s\n",
                        record.topic(),
                        record.partition(),
                        record.key(),
                        record.value());
            }
            consumer.commitSync();
        }
    }
}
